const Instruction = require('./Instruction');
const TaskIdGenerator = require('../../utils/taskIdGenerator');

class InstructionController {
  // 获取所有指令
  static getAllInstructions(req, res) {
    Instruction.findAll((err, instructions) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '获取指令列表失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: instructions
      });
    });
  }

  // 获取当前指令（未完成的指令）
  static getCurrentInstructions(req, res) {
    Instruction.findCurrentInstructions((err, instructions) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '获取当前指令列表失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: instructions
      });
    });
  }

  // 获取历史指令（已完成和已撤销的指令）
  static getHistoryInstructions(req, res) {
    Instruction.findHistoryInstructions((err, instructions) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '获取历史指令列表失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: instructions
      });
    });
  }

  // 根据ID获取指令
  static getInstructionById(req, res) {
    const { id } = req.params;
    
    Instruction.findById(id, (err, instruction) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询指令失败',
          error: err.message
        });
      }
      
      if (!instruction) {
        return res.status(404).json({
          success: false,
          message: '指令未找到'
        });
      }
      
      res.json({
        success: true,
        data: instruction
      });
    });
  }

  // 创建新指令
  static createInstruction(req, res) {
    const {
      taskId, taskType, palletId, startLocation, targetLocation,
      startDevice, endDevice, materialCode, materialName,
      executeQuantity
    } = req.body;
    
    // 验证必填字段
    if (!taskType) {
      return res.status(400).json({
        success: false,
        message: '任务类型为必填项'
      });
    }
    
    // 如果提供了任务号，则使用提供的任务号
    if (taskId) {
      const newInstruction = new Instruction(
        null,
        taskId,
        taskType,
        palletId,
        startLocation,
        targetLocation,
        startDevice,
        endDevice,
        materialCode,
        materialName,
        executeQuantity,
        'not_issued', // 默认状态为未下发
        null,
        null
      );
      
      // 保存指令
      newInstruction.save((err, result) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '创建指令失败',
            error: err.message
          });
        }
        
        res.status(201).json({
          success: true,
          message: '指令创建成功',
          data: { id: result.id, ...newInstruction }
        });
      });
    } else {
      // 如果没有提供任务号，则生成递增的纯数字任务号
      // 首先获取当前最大的指令ID
      Instruction.getMaxId((err, maxIdResult) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '获取最大ID失败',
            error: err.message
          });
        }
        
        // 生成下一个递增的任务号
        const nextTaskId = TaskIdGenerator.generateNextTaskId(maxIdResult.maxId || 0, 200);
        
        const newInstruction = new Instruction(
          null,
          nextTaskId,
          taskType,
          palletId,
          startLocation,
          targetLocation,
          startDevice,
          endDevice,
          materialCode,
          materialName,
          executeQuantity,
          'not_issued', // 默认状态为未下发
          null,
          null
        );
        
        // 保存指令
        newInstruction.save((err, result) => {
          if (err) {
            return res.status(500).json({
              success: false,
              message: '创建指令失败',
              error: err.message
            });
          }
          
          res.status(201).json({
            success: true,
            message: '指令创建成功',
            data: { id: result.id, taskId: nextTaskId, ...newInstruction }
          });
        });
      });
    }
  }

  // 更新指令状态
  static updateInstructionStatus(req, res) {
    const { id } = req.params;
    const { status, completionMethod, completionTime } = req.body;
    
    Instruction.updateStatus(id, status, completionMethod, completionTime, (err, result) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '更新指令状态失败',
          error: err.message
        });
      }
      
      if (!result.updated) {
        return res.status(404).json({
          success: false,
          message: '指令未找到或状态未更新'
        });
      }
      
      res.json({
        success: true,
        message: '指令状态更新成功',
        data: result
      });
    });
  }

  // 强制过账指令
  static forcePostInstruction(req, res) {
    const { id } = req.params;
    
    Instruction.forcePost(id, (err, result) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '强制过账指令失败',
          error: err.message
        });
      }
      
      if (!result.updated) {
        return res.status(404).json({
          success: false,
          message: '指令未找到或无法强制过账'
        });
      }
      
      res.json({
        success: true,
        message: '指令强制过账成功',
        data: result
      });
    });
  }

  // 撤销指令
  static cancelInstruction(req, res) {
    const { id } = req.params;
    
    Instruction.cancel(id, (err, result) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '撤销指令失败',
          error: err.message
        });
      }
      
      if (!result.updated) {
        return res.status(404).json({
          success: false,
          message: '指令未找到或无法撤销'
        });
      }
      
      res.json({
        success: true,
        message: '指令撤销成功',
        data: result
      });
    });
  }

  // 删除指令
  static deleteInstruction(req, res) {
    const { id } = req.params;
    
    Instruction.delete(id, (err, result) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '删除指令失败',
          error: err.message
        });
      }
      
      if (!result.deleted) {
        return res.status(404).json({
          success: false,
          message: '指令未找到'
        });
      }
      
      res.json({
        success: true,
        message: '指令删除成功'
      });
    });
  }
}

module.exports = InstructionController;